import {login, logout, getInfo} from '@/api/auth'
import {getToken, setToken, removeToken} from '@/utils/auth'

const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    userInfo: {},
    isLogin: false,
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_USER_INFO: (state, userInfo) => {
      state.userInfo = userInfo
    },
    SET_LOGIN_STATE: (state, isLogin) => {
      state.isLogin = isLogin
    }
  },

  actions: {
    // 登录
    Login({commit}, loginForm) {
      const data = {
        "userName": loginForm.userName.trim(),
        "password": loginForm.password
      }
      return new Promise((resolve, reject) => {
        login(data).then(res => {
          setToken(res.data.token)
          commit('SET_TOKEN', res.data.token)
          commit('SET_LOGIN_STATE', true)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({commit, state}) {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
          const user = res.data
          const avatar = user.avatar == "" ? require("@/assets/images/profile.jpg") : user.avatar;
          commit('SET_LOGIN_STATE', true)
          commit('SET_NAME', user.userName)
          commit('SET_AVATAR', avatar)
          commit('SET_USER_INFO', user)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 退出系统
    LogOut({commit, state}) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_AVATAR', '')
          commit('SET_USER_INFO', {})
          commit('SET_LOGIN_STATE', false)
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
  }
}

export default user